import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import './TeacherPage.css';
import { Teacher, stageOptions } from '../../shared/models';
import { useData } from '../../shared/DataContext';
import TeacherTable from './components/TeacherTable';
import AddEditTeacherModal from './components/AddEditTeacherModal';
import ConfirmModal from './components/ConfirmModal';
import TeacherDetailModal from './components/TeacherDetailModal';
const TeacherPage: React.FC = () => {
  const { teachers, createTeacher, updateTeacher, deleteTeacher } = useData();
  const [filteredTeachers, setFilteredTeachers] = useState<Teacher[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedSubject, setSelectedSubject] = useState('');
  const [selectedStage, setSelectedStage] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [selectedDepartment, setSelectedDepartment] = useState('');
  const [showAddEditModal, setShowAddEditModal] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedTeacher, setSelectedTeacher] = useState<Teacher | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const itemsPerPageOptions = [5, 10, 20, 50]; // 每页显示条数选项

  // 选项数据定义
  const subjectOptions = [
    { value: 'chinese', label: '语文' },
    { value: 'math', label: '数学' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' },
    { value: 'history', label: '历史' },
    { value: 'geography', label: '地理' },
    { value: 'politics', label: '政治' }
  ];

  // 从shared/models.ts导入的stageOptions，添加全部阶段选项
  const enhancedStageOptions = [
    { value: 'all', label: '全部阶段' },
    ...stageOptions
  ];

  const positionOptions = [
    { value: 'teacher', label: '教师' },
    { value: 'headteacher', label: '班主任' },
    { value: 'director', label: '教导主任' },
    { value: 'principal', label: '校长' }
  ];

  const educationOptions = [
    { value: 'bachelor', label: '本科' },
    { value: 'master', label: '硕士' },
    { value: 'doctor', label: '博士' },
    { value: 'associate', label: '大专' }
  ];

  const statusOptions = [
    { value: 'active', label: '在职' },
    { value: 'leave', label: '请假' },
    { value: 'resigned', label: '已离职' },
    { value: 'retired', label: '已退休' }
  ];

  const departmentOptions = [
    { value: 'chinese', label: '语文组' },
    { value: 'math', label: '数学组' },
    { value: 'english', label: '英语组' },
    { value: 'science', label: '科学组' },
    { value: 'humanities', label: '人文组' },
    { value: 'administration', label: '行政部门' }
  ];

  // 计算总页数
  const totalPages = Math.ceil(filteredTeachers.length / itemsPerPage);

  // 处理每页显示条数变化
  const handleItemsPerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setItemsPerPage(parseInt(e.target.value, 10));
    setCurrentPage(1); // 重置到第一页
  };

  // 跳转到指定页码
  const handlePageJump = (pageNum: number) => {
    if (pageNum >= 1 && pageNum <= totalPages) {
      setCurrentPage(pageNum);
    }
  };

  // 快速跳转到首页或末页
  const goToFirstPage = () => setCurrentPage(1);
  const goToLastPage = () => setCurrentPage(totalPages);

  // 筛选教师数据
  useEffect(() => {
    let result = [...teachers];

    // 搜索筛选
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(teacher => 
        teacher.name.toLowerCase().includes(term) ||
        teacher.id.toLowerCase().includes(term) ||
        teacher.phone.includes(term) ||
        teacher.email.toLowerCase().includes(term)
      );
    }

    // 科目筛选
    if (selectedSubject) {
      result = result.filter(teacher => teacher.subject === selectedSubject);
    }

    // 阶段筛选
    if (selectedStage) {
      result = result.filter(teacher => teacher.stage === selectedStage || teacher.stage === 'all');
    }

    // 状态筛选
    if (selectedStatus) {
      result = result.filter(teacher => teacher.status === selectedStatus);
    }

    // 部门筛选
    if (selectedDepartment) {
      result = result.filter(teacher => teacher.department === selectedDepartment);
    }

    setFilteredTeachers(result);
    setCurrentPage(1); // 重置到第一页
  }, [teachers, searchTerm, selectedSubject, selectedStage, selectedStatus, selectedDepartment]);

  // 获取当前页的数据
  const currentTeachers = filteredTeachers.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  // 处理查看教师详情
  const handleViewDetail = (teacher: Teacher) => {
    setSelectedTeacher(teacher);
    setShowDetailModal(true);
  };

  // 关闭详情模态框
  const handleCloseDetailModal = () => {
    setShowDetailModal(false);
    setSelectedTeacher(null);
  };

  // 处理添加教师
  const handleAddTeacher = () => {
    setSelectedTeacher(null);
    setIsEditing(false);
    setShowAddEditModal(true);
  };

  // 处理编辑教师
  const handleEditTeacher = (teacher: Teacher) => {
    setSelectedTeacher(teacher);
    setIsEditing(true);
    setShowAddEditModal(true);
  };

  // 处理删除教师
  const handleDeleteTeacher = (teacher: Teacher) => {
    setSelectedTeacher(teacher);
    setShowConfirmModal(true);
  };

  // 确认删除教师
  const confirmDeleteTeacher = async () => {
    if (selectedTeacher) {
      try {
        // 删除教师
        await deleteTeacher(selectedTeacher.id);
        setShowConfirmModal(false);
        setSelectedTeacher(null);
      } catch (error) {
        console.error('删除教师失败:', error);
        alert('删除教师失败，请稍后再试');
      }
    }
  };

  // 处理保存教师
  const handleSaveTeacher = async (teacherData: Teacher) => {
    try {
      if (isEditing && selectedTeacher) {
        // 更新现有教师
        await updateTeacher(selectedTeacher.id, teacherData);
      } else {
        // 添加新教师
        // 移除id和时间戳字段，因为这些由后端生成
        const { id, createdAt, updatedAt, ...newTeacherData } = teacherData;
        await createTeacher(newTeacherData);
      }
      setShowAddEditModal(false);
    } catch (error) {
      console.error('保存教师失败:', error);
      alert('保存教师失败，请稍后再试');
    }
  };

  // 导出教师数据
  const handleExportTeachers = () => {
    if (filteredTeachers.length === 0) {
      alert('没有可导出的数据');
      return;
    }

    // 转换教师数据为Excel格式所需的数据
    const excelData = filteredTeachers.map(teacher => {
      const subjectText = subjectOptions.find(opt => opt.value === teacher.subject)?.label || teacher.subject;
      const gradeText = stageOptions.find(opt => opt.value === teacher.stage)?.label || teacher.stage;
      const positionText = positionOptions.find(opt => opt.value === teacher.position)?.label || teacher.position;
      const educationText = educationOptions.find(opt => opt.value === teacher.education)?.label || teacher.education;
      const statusText = statusOptions.find(opt => opt.value === teacher.status)?.label || teacher.status;
      const departmentText = departmentOptions.find(opt => opt.value === teacher.department)?.label || teacher.department;

      return {
        '教师ID': teacher.id,
        '姓名': teacher.name,
        '性别': teacher.gender === 'male' ? '男' : '女',
        '科目': subjectText,
        '教授阶段': gradeText,
        '职位': positionText,
        '学历': educationText,
        '出生日期': new Date(teacher.dateOfBirth).toLocaleDateString('zh-CN'),
        '入职日期': new Date(teacher.hireDate).toLocaleDateString('zh-CN'),
        '联系电话': teacher.phone,
        '电子邮箱': teacher.email,
        '家庭住址': teacher.address,
        '状态': statusText,
        '部门': departmentText,
        '薪资等级': teacher.salaryLevel || '-',
        '资格证书': teacher.qualifications?.join('、') || '-'
      };
    });

    // 创建工作簿和工作表
    const ws = XLSX.utils.json_to_sheet(excelData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '教师数据');

    // 设置文件名，包含当前日期时间以避免覆盖
    const now = new Date();
    const timestamp = now.getFullYear() + 
                     String(now.getMonth() + 1).padStart(2, '0') + 
                     String(now.getDate()).padStart(2, '0') + 
                     '_' + 
                     String(now.getHours()).padStart(2, '0') + 
                     String(now.getMinutes()).padStart(2, '0');

    // 导出Excel文件
    XLSX.writeFile(wb, `教师数据_${timestamp}.xlsx`);

    alert(`成功导出 ${filteredTeachers.length} 名教师数据到Excel文件`);
  };

  return (
    <div className="teacher-page">
      <div className="page-header">
        <h1>教师管理</h1>
        <div className="header-actions">
          <button className="btn-export" onClick={handleExportTeachers}>
            导出数据
          </button>
          <button className="btn-primary" onClick={handleAddTeacher}>
            添加教师
          </button>
        </div>
      </div>

      <div className="filter-section">
        <div className="search-box">
          <input
            type="text"
            placeholder="搜索教师姓名、工号、电话或邮箱..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="search-input"
          />
        </div>
        <div className="filter-controls">
          <select
            value={selectedSubject}
            onChange={(e) => setSelectedSubject(e.target.value)}
            className="filter-select"
          >
            <option value="">所有科目</option>
            {subjectOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          
          <select
            value={selectedStage}
            onChange={(e) => setSelectedStage(e.target.value)}
            className="filter-select"
          >
            <option value="">所有阶段</option>
            {enhancedStageOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          
          <select
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="filter-select"
          >
            <option value="">所有状态</option>
            {statusOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
          
          <select
            value={selectedDepartment}
            onChange={(e) => setSelectedDepartment(e.target.value)}
            className="filter-select"
          >
            <option value="">所有部门</option>
            {departmentOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="table-section">
        <TeacherTable
          teachers={currentTeachers}
          onViewDetail={handleViewDetail}
          onEdit={handleEditTeacher}
          onDelete={handleDeleteTeacher}
        />
      </div>

      <div className="pagination">
        <div className="pagination-controls">
          <button 
            onClick={goToFirstPage} 
            disabled={currentPage === 1}
            className="pagination-btn"
          >
            首页
          </button>
          <button 
            onClick={() => handlePageJump(currentPage - 1)} 
            disabled={currentPage === 1}
            className="pagination-btn"
          >
            上一页
          </button>
          
          <span className="pagination-info">
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          
          <button 
            onClick={() => handlePageJump(currentPage + 1)} 
            disabled={currentPage === totalPages}
            className="pagination-btn"
          >
            下一页
          </button>
          <button 
            onClick={goToLastPage} 
            disabled={currentPage === totalPages}
            className="pagination-btn"
          >
            末页
          </button>
        </div>
        
        <div className="items-per-page">
          <label>每页显示：</label>
          <select 
            value={itemsPerPage} 
            onChange={handleItemsPerPageChange}
            className="items-per-page-select"
          >
            {itemsPerPageOptions.map(option => (
              <option key={option} value={option}>
                {option} 条
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* 添加/编辑教师模态框 */}
      <AddEditTeacherModal
        isOpen={showAddEditModal}
        onClose={() => setShowAddEditModal(false)}
        onSave={handleSaveTeacher}
        teacher={selectedTeacher}
        isEditing={isEditing}
      />

      {/* 确认删除模态框 */}
      <ConfirmModal
        isOpen={showConfirmModal}
        onClose={() => setShowConfirmModal(false)}
        onConfirm={confirmDeleteTeacher}
        title="确认删除"
        message={`确定要删除教师「${selectedTeacher?.name}」吗？此操作不可撤销。`}
      />

      {/* 教师详情模态框 */}
      <TeacherDetailModal
        isOpen={showDetailModal}
        onClose={handleCloseDetailModal}
        teacher={selectedTeacher}
      />
    </div>
  );
};

export default TeacherPage;